import React, { Component } from 'react';
import { withRouter, Route } from 'react-router-dom';
import { inject, observer } from 'mobx-react';

import {  Reply, AtSomeone } from 'weaver-mobile-page';
import { Toast } from 'weaver-mobile';
import base from "../../util/base";

import TobTab from './TopTab';
import ContentList from './ContentList';
import RelatedResources from './RelatedResources';
import QuoteHead from './QuoteHead';
import * as EmSDK from "../../util/emSDK";
import $ from 'jquery';
import { Tools } from 'weaver-mobile';
import { toJS } from 'mobx';
import Base from '../../util/base';
const getLabel = Tools.getLabel;

@withRouter
@inject('wfCommunicateStore', 'wfSignListStore')
@observer
export default class Main extends Component {
    componentWillMount(){
      const { wfCommunicateStore, commonParams} = this.props;
      const {  comSetStoreState  } = wfCommunicateStore;
      comSetStoreState({communicateReplyVisible: this.setDetailReplyVisible})
      wfCommunicateStore.init(commonParams);  
    }

    componentDidMount() {
      const {wfCommunicateStore, signReplyInfo: {reply_status}, location } = this.props;
      const { comSetStoreState, hasLoaded } = wfCommunicateStore;
      const pathname = location && location.pathname || "";
      EmSDK.resetBottomBtn();
      comSetStoreState({ signRelyFlag: reply_status });
      hasLoaded && window.formImgLazyLoad($(".wf-commu-scrollContent"));
    }
    componentDidUpdate() {
      const { hasLoaded} = this.props.wfCommunicateStore;
      hasLoaded && window.formImgLazyLoad($('.wea-workflow-communication-list'));//图片懒加载
    }

    componentWillReceiveProps(nextProps, nextState) {
      const location = this.props.location || {};
      const nextLocation = nextProps.location || {};
      const pathname = location.pathname || "";
      const nextPathname = nextLocation.pathname || "";
      console.log("Communicate componentWillReceiveProps", location, nextLocation);
      if (pathname !== nextPathname) {
          if(nextPathname === '/req/communicateSearch') {
            EmSDK.setReqEmTopNav(nextPathname, getLabel('512465', "搜索交流"));
          }
          if(nextPathname === '/req/communicateSearch/discussant') {
            EmSDK.setReqEmTopNav(nextPathname, getLabel('512466',"请选择发表人"));
          }
      }
      EmSDK.resetBottomBtn();
  }
   
    componentWillUnmount() {
      const { clearStore, closeAllModel } = this.props.wfCommunicateStore;
      clearStore();
      closeAllModel();
      base.wfSignListStore.initDatas({pgnumber: 1});
    }

    //设置Reply组件的显隐
    setDetailReplyVisible = (val) => {
      const replyRef = this.replyRef; // 避免某一瞬间找不到this.replyRef
      if (replyRef) {
        replyRef.setVisible(val, () => {
          if(val){//防止focus的时候，因为获取焦点而自动显示
            replyRef.getInputFocus('last');
          }
        });
      } else {
        window.setTimeout(()=>{
          this.setDetailReplyVisible();
        },0)
      }
    }

    submit = (data) => {
      const { wfCommunicateStore, clearReplyInfo } = this.props;
      const { publishCommunicate, saveComment, replyType, comSetStoreState } = wfCommunicateStore;
      let str = '';
      if(data.text != '') {
        str = data.text.replace(/<\/?[^>]*>/g, '');
        str = str.replace(/[\u200B-\u200D\uFEFF]/g, "");
        str = str.replace(/\n/g,'');
        str = str.replace("&#8203;", "").replace(/&nbsp;/g, '');
        str = str.trim();
      } 
      if(str === "" || str === "<p><br></p>") {
        Toast.info(getLabel('382648', "请输入交流内容"), 1);
        return
      }
      clearReplyInfo();
      replyType === '' ? publishCommunicate(data) : saveComment(data)
      comSetStoreState(
        {
          needPanel: false, 
          replyType: '', 
          placeholderValue: getLabel('512567', '交流内容...')
        });
    }

    doScrollEvent() {
      window.formImgLazyLoad($(".wf-commu-scrollContent"));
    }

    renderAt = (item) => {
      const { wfCommunicateStore, history } = this.props;
      const { atUserStore, initAtData, reqOperators = []} = wfCommunicateStore;
      const template2 = {
        default: {
            theme: 'col2_row2',
            dataKeys: ['data', 'jobtitlename', 'subcompanyname', 'departmentname'],
        },
      };
      return (
        <div className={`communicate-atSome`} 
             onClick={() => {history.push(atUserStore.path)}}
        >
          {item}
            <AtSomeone
              datas={toJS(reqOperators)}
              template={template2}
              store={atUserStore}
              onOk={this.setContentValue}
              imgSrcDataKey={'icon'}
              nameDataKey={'data'}
          />
        </div>
      )
    }
    setContentValue = (datas) => {
      const { wfCommunicateStore } = this.props;
      const { replyComment, commentReplyStoreMap,quoteReplyStoreMap,replyType,communicateReply,} = wfCommunicateStore;
      let { detailReply, quoteReply  } = wfCommunicateStore;
      if (replyComment) {
        detailReply = commentReplyStoreMap[replyComment.replyId];
        quoteReply = quoteReplyStoreMap[replyComment.replyId]
      }
      let replyStore = null;
      switch( replyType) {
        case('quote'): replyStore = quoteReply; break;
        case('comment'): replyStore = detailReply; break;
        default: replyStore = communicateReply;
      }
      const replyRef = this.replyRef;
      if (datas && datas.length > 0) {
        let html = '';
        datas.map((item) => {
          const value = `@${item.data.replace(/\(/g,'（').replace(/\)/g,'）')}`;
          html += `<a contenteditable="false" atsome="@${item.id}" atsome-uid="${item.id}" atsome-name="${item.data.replace(/\(/g,'（').replace(/\)/g,'）')}" target="_blank" style="cursor:pointer;text-decoration:none !important;color:#2777c1!important;" href="javascript:void(0)">${value}</a>&nbsp;`;
        });
        replyRef.replyRef.changeTextValue(html);
        replyStore.setState({
          atLists: [
            ...toJS(replyStore.atLists),
            ...datas
          ]
        })
      }
    }
    render() {
      const { wfCommunicateStore, signReplyInfo,clearReplyInfo} = this.props;
      const { tabKey } = base.wfGlobalStore;
      const { page, hasLoaded, leftConfig, placeholderValue,replyComment,  
          commentReplyStoreMap,quoteReplyStoreMap,replyType,communicateReply,
          onMaskClick, quoteInfo, needPanel, hasSubmitRight = false
        } = wfCommunicateStore;
     
      let { detailReply, quoteReply  } = wfCommunicateStore;
      if (replyComment) {
        detailReply = commentReplyStoreMap[replyComment.replyId];
        quoteReply = quoteReplyStoreMap[replyComment.replyId];
      }
      let replyStore = null;
      switch( replyType) {
        case('quote'): replyStore = quoteReply; break;
        case('comment'): replyStore = detailReply; break;
        default: replyStore = communicateReply;
      }
      const showReply = page ==='allCommunications' || page ==='relatedMe';
     
      return (
          <div 
              className={`wf-commu ${tabKey == 'communicate' ? 'wf-commu-tab' :''}`} 
              style={{'paddingBottom' : (page !== "allCommunications" ||  !hasSubmitRight ) ? '0px' : '45px'}}
          >
              <TobTab clearReplyInfo={clearReplyInfo}/>
              <div 
                  className={`wf-commu-scrollContent ${tabKey == 'communicate' ? 'wf-comu-scrollContent-tab' :''}`}  
                  onScroll={this.doScrollEvent.bind(this)}
                  style={{width: '100%', height: '100%', overflow: 'auto'}}
              >
                  { (page == 'allCommunications' || page == 'relatedMe')  && hasLoaded && <ContentList /> }
                  { page == 'relatedResource'  && <RelatedResources prefixCls={'wf-communication'}/> }
              </div>  
              {
                showReply 
                  && [
                    <React.Fragment>{needPanel && <div className="wf-commu-reply-mask"></div>} </React.Fragment>
                    ,              
                    <div className="footer-wrap">
                      { 
                        needPanel 
                          && <QuoteHead 
                                store={wfCommunicateStore} 
                                clearReplyInfo={clearReplyInfo}
                                signReplyInfo={signReplyInfo}
                                quoteInfo={quoteInfo}
                                setDetailReplyVisible={this.setDetailReplyVisible}
                            />
                      } 
                      { 
                        hasLoaded 
                          && hasSubmitRight
                          && <Reply
                                wrappedComponentRef={ref => this.replyRef = ref}
                                store={replyStore}      
                                visible={false}                                   
                                leftConfig={leftConfig}
                                showOutInput={ page === 'allCommunications' ? true:false}
                                placeholder={placeholderValue}
                                onMaskClick={onMaskClick}
                                onImgChange={this.onImgChange}
                                onSubmitButtonClick={this.submit}
                                renderAt={this.renderAt}
                          />  
                    }   
                    </div>
                  ]
              } 
          </div>
      )
    }
  }
   